/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.groupofdoom.beans;

import edu.chl.groupofdoom.entities.Comment;
import edu.chl.groupofdoom.entities.Torrent;
import edu.chl.groupofdoom.entities.User;
import edu.chl.groupofdoom.jpa.Mapper;
import edu.chl.groupofdoom.support.SupportClass;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 * View bean for torrents
 *
 * @author Martin Agfjord
 */
@ManagedBean(name = "TorrentBean")
@RequestScoped
public class TorrentBean implements Serializable {

    private Torrent currentTorrent;
    private String comment;

    public TorrentBean() {
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Torrent getCurrentTorrent() {
        return currentTorrent;
    }

    public void setCurrentTorrent(Torrent currentTorrent) {
        this.currentTorrent = currentTorrent;
    }

    /**
     * If there is a torrent in the current request scope this method
     * does nothing. Otherwise it retrieves a torrent from the database.
     * Main purpose of this class is to make it possible to minimize cpu/hard drive/memory power
     * and only request objects if needed
     */
    public void checkIfTorrentExists() {
        //If the requested torrent is the same as the one in the bean, do nothing
        //otherwise if no torrent or a different one, create one from the id.
        long id = 0;
        try {
            HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            id = Long.parseLong(req.getParameter("id"));
            if (currentTorrent.getId() != id) {
                currentTorrent = Mapper.getTorrent(id);
            }

        } catch (NullPointerException e) {
            currentTorrent = Mapper.getTorrent(id);
        } catch (Exception e) {
        }
    }
    /**
     * Adds a comment to a torrent
     */
    public void addComment() {
        User sessionUser = SupportClass.getUserBean().getUser();
        currentTorrent.getComments().add(new Comment(sessionUser, comment));
        Mapper.updateTorrent(currentTorrent);
        comment = "";
    }
}
